接續到上一篇的RecyclerView,今天要來分享一下點擊事件
先創立一個interface接口
void onItemClick(int position);
}
接著去設定一個變數引用他
private OnItemClickListener listener;
創建一個呼叫他的方法
public void setOnItemClickListener(OnItemClickListener listener) {
this.listener = listener;
}
然後到原本的viewholder去設定
itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (listener != null) {
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION) {
listener.onItemClick(position);
}
}
}
});
接著回到主程式就可以調用了
myAdapter.setOnItemClickListener(new MyAdapter.OnItemClickListener() {
@Override
public void onItemClick(int position) {
String itemNumber = dataList.get(position).get("num");
Toast.makeText(MainActivity.this,"點擊了" + itemNumber + "號",Toast.LENGTH_SHORT).show();
}
});
Adatper的完整程式碼
package com.example.itdemo;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
import java.util.HashMap;
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> {
private ArrayList<HashMap<String,String>> dataList;
private OnItemClickListener listener;
public MyAdapter(ArrayList<HashMap<String,String>> dataList) {
this.dataList = dataList;
}
@NonNull
@Override
public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
// 創建 ViewHolder 並連結項目佈局檔案
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item, parent, false);
return new MyViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull MyAdapter.MyViewHolder holder, int position) {
// 在這裡綁定數據到 ViewHolder 的 View
String itemView = String.valueOf(dataList.get(position));
holder.textView.setText(dataList.get(position).get("num"));
holder.textView5.setText(dataList.get(position).get("score"));
}
@Override
public int getItemCount() {
return dataList.size();
}
public void setOnItemClickListener(OnItemClickListener listener) {
this.listener = listener;
}
public class MyViewHolder extends RecyclerView.ViewHolder {
private TextView textView;
private TextView textView5;
public MyViewHolder(@NonNull View itemView) {
super(itemView);
textView = itemView.findViewById(R.id.textView);
textView5 = itemView.findViewById(R.id.textView5);
itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(listener != null){
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION){
listener.onItemClick(position);
}
}
}
});
}
}
public interface OnItemClickListener {
void onItemClick(int position);
}
}
成果如下